package com.markhsiu.MiniMQ.remote.transport.netty.handler;

import java.util.Map;

import com.markhsiu.MiniMQ.model.Message;
import com.markhsiu.MiniMQ.model.constant.MessageSourceEnum;
import com.markhsiu.MiniMQ.remote.MessageProcessor;
import com.markhsiu.MiniMQ.remote.transport.netty.NettyChannelProcessor;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by Mark Hsiu on 2017/2/8.
 */
public class NettySeverHandler extends ChannelInboundHandlerAdapter {

    private Map<MessageSourceEnum, MessageProcessor> handlers;
    public NettySeverHandler(Map<MessageSourceEnum, MessageProcessor> handlers) {
		this.handlers = handlers;
	}

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        Message message = (Message)msg;
        this.handler(ctx,message);
    }
    
    private void handler(ChannelHandlerContext ctx, Message message){
    	if(message.getMessageID() == null){
			throw new RuntimeException("messageID is null");
		}
    	
    	MessageProcessor messageProcessor =  handlers.get(message.getSource());
    	messageProcessor.handler(message,new NettyChannelProcessor(ctx));
    }

//    @Override
//    public void channelReadComplete(ChannelHandlerContext ctx) {
//        ctx.flush();
//    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}
